package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author cuche
 * @date 19.05.2014
 * 
 * This class handles the ZIP files that come from the FileUploadServlet.
 *  
 */
public class FileUnziper {
	
	/**
	 * This method takes a ZIP file and iterates through the stream and
	 * gets every Entry in the ZIP
	 * 
	 * @param zipFile
	 * @param outputDir
	 */

    public static void unzipFileTo(File zipFile, String outputDir) {
        // create a buffer to improve copy performance
        byte[] buffer = new byte[2048];
        ZipInputStream stream = null;
        try {
            InputStream theFile = new FileInputStream(zipFile);
            stream = new ZipInputStream(theFile);

            // iterate through the stream. getNextEntry call will return a 
            //ZipEntry for each file in the stream
            ZipEntry entry;
            while((entry = stream.getNextEntry()) != null) {
            	// increment counter value and add it to the file names
            	int counterValue = FileCounter.getInstance().getNextCounter();
            	String outPath = outputDir + "/"+ counterValue + "_" + entry.getName();
                saveEntry(outPath, stream, buffer);
            }
                        
        } catch (FileNotFoundException e) {
			e.getLocalizedMessage();
		} catch (IOException e) {
			e.getLocalizedMessage();
		}
        finally {
        	if (stream != null)
				try {
					stream.close();
				} catch (IOException e) {
					e.getLocalizedMessage();
				}
        }
    }
        
    /**
     * gets the the entry of the stream from before
     * and reads the raw data until there is nothing left
     * 
     * 
     * @param outputPath
     * @param stream
     * @param buffer
     * @throws IOException
     */
    private static void saveEntry(String outputPath, ZipInputStream stream, byte[] buffer) throws IOException {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(outputPath);
            int len = 0;
            while ((len = stream.read(buffer)) > 0) {
                output.write(buffer, 0, len);
            }
        }
        finally {
            if (output != null) output.close();
            output.flush();
        }
    }
}